package com.len.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.len.base.BaseController;
import com.len.core.annotation.Log;
import com.len.entity.*;
import com.len.exception.MyException;
import com.len.service.DemandService;
import com.len.service.ProductDemandService;
import com.len.service.QuotationService;
import com.len.util.BeanUtil;
import com.len.util.JsonUtil;
import com.len.util.ReType;
import com.len.util.UploadUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("demand")
public class DemandController extends BaseController {

    @Autowired
    private DemandService demandService;
    @Autowired
    private QuotationService quotationService;
    @Autowired
    UploadUtil uploadUtil;
    @Autowired
    private ProductDemandService productDemandService;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    @GetMapping(value = "showAddDemand")
    public String goAddUser(Model model) {
        
        Date date = new Date();
        String id =sdf.format(date) ;
        //生成订单编号
        model.addAttribute("id", id);
        return "/act/demand/add-demand";
    }
    /**
     * 头像上传 目前首先相对路径
     */
    @PostMapping(value = "upload")
    @ResponseBody
    public JsonUtil imgUpload(HttpServletRequest req, @RequestParam("file") MultipartFile file,
                              ModelMap model) {
        String fileName = uploadUtil.upload(file);
        JsonUtil j = new JsonUtil();
        j.setMsg(fileName);
        return j;
    }
    @Log(desc = "添加生产通知单", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation(value = "/addDemand", httpMethod = "POST", notes = "添加生产通知单")
    @PostMapping("/addDemand")
    @ResponseBody
    public JsonUtil addMenu(@RequestBody JSONObject demand, Model model) {
        List<TProductDemand> productDemands = JSON.parseArray(demand.getString("taskDetails"),TProductDemand.class);
        demand.remove("taskDetails");
        TDemand tDemand = JSONObject.toJavaObject(demand,TDemand.class);
        if(productDemands.size()>0){
            TProductDemand td = productDemands.get(0);
            tDemand.setForeignHandle(td.getForeignHandle());
            tDemand.setForeignPrient(td.getForeignPrient());
            tDemand.setPeriod(td.getPeriod());
            tDemand.setWeight(td.getWeight());
        }
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setFlag(false);
        if (demand == null) {
            jsonUtil.setMsg("获取数据失败");
            return jsonUtil;
        }
        try {
            tDemand.setAddTime(new Date());
            demandService.insertSelective(tDemand);
            if(productDemands.size()>0){
                for(int i = 0;i<productDemands.size();i++){
                    productDemands.get(i).setOrderNo(tDemand.getOrderNo());
                    productDemandService.insert(productDemands.get(i));
                }
            }
            jsonUtil.setMsg("添加成功");
        } catch (MyException e) {
            e.printStackTrace();
            jsonUtil.setMsg("添加失败");
        }
        return jsonUtil;
    }

    @GetMapping(value = "/showdemand")
    @RequiresPermissions("demand:show")
    public String showUser(Model model) {
        return "/act/demand/demandList";
    }

    @RequestMapping("/showDemandList")
    @ResponseBody
    @RequiresPermissions("demand:show")
    public ReType showUser(Model model, TDemand demand, String page, String limit) {
        demand.setOrderNo("111");
        ReType reType = demandService.show(demand, Integer.valueOf(page), Integer.valueOf(limit));
        return demandService.show(demand, Integer.valueOf(page), Integer.valueOf(limit));
    }

    @RequestMapping("/showProductDemand")
    @ResponseBody
    public ReType showDemand(String id, Model model, boolean detail) {
        ReType reType = new ReType();
        List<TProductDemand> taskDetails = productDemandService.selectAllByOrderNo(id);
        reType.setData(taskDetails);
        return reType;
    }
    @Log(desc = "删除生产通知单", type = Log.LOG_TYPE.DEL)
    @PostMapping("/delDemand")
    @ResponseBody
    public JsonUtil del(String id) {
        JsonUtil jsonUtil = new JsonUtil();
        try {
            TDemand demand = demandService.selectByPrimaryKey(id);
            productDemandService.delAllByOrderNo(demand.getOrderNo());
            demandService.deleteByPrimaryKey(id);
            jsonUtil.setMsg("删除成功");
            return jsonUtil;
        }catch (Exception e){
            e.printStackTrace();
        }

        jsonUtil.setMsg("删除失败");
        return jsonUtil;
    }

    @Log(desc = "更新生产通知单", type = Log.LOG_TYPE.ADD)
    @PostMapping("/updateDemand")
    @ResponseBody
    public JsonUtil updateDemand(@RequestBody JSONObject demand) {
        List<TProductDemand> productDemands = JSON.parseArray(demand.getString("taskDetails"),TProductDemand.class);
        demand.remove("taskDetails");
        TDemand tDemand = JSONObject.toJavaObject(demand,TDemand.class);
        TDemand oldDemand = demandService.selectByPrimaryKey(tDemand.getId());
        BeanUtil.copyNotNullBean(tDemand, oldDemand);
        demandService.updateByPrimaryKeySelective(oldDemand);

        for(int i =0;i< productDemands.size();i++){
            TProductDemand oldTaskDetail = productDemandService.selectByPrimaryKey(productDemands.get(i).getId());
            if(null!=oldTaskDetail) {
                BeanUtil.copyNotNullBean(productDemands.get(i), oldTaskDetail);
                productDemandService.updateByPrimaryKeySelective(oldTaskDetail);
            }else {
                productDemandService.insert(productDemands.get(i));
            }
        }
        return JsonUtil.sucess("保存成功");
    }

    @GetMapping(value = "detailDemand")
    public String goUpdateUser(String id, Model model, boolean detail) {
        if (StringUtils.isNotEmpty(id)) {
            TDemand demand = demandService.selectByPrimaryKey(id);
            List<TProductDemand> taskDetails = productDemandService.selectAllByOrderNo(demand.getOrderNo());
            model.addAttribute("demand", demand);
            model.addAttribute("taskDetail", taskDetails);
        }

        model.addAttribute("detail", detail);
        return "/act/demand/update-demand";
    }

    @RequestMapping("/trans")
    @ResponseBody
//    @RequiresPermissions("product:show")
    public JsonUtil trans(String id) {
        JsonUtil jsonUtil = new JsonUtil();
        try {
            TDemand demand = demandService.selectByPrimaryKey(id);
            List<TQuotation>  tQuotations = quotationService.selectListByOrderNo(demand.getOrderNo());
            if(tQuotations.size() != 0){
                jsonUtil.setMsg("已有相应合同编号的报价单");
                return jsonUtil;
            }

            TQuotation quotation = new TQuotation();
            quotation.setOrderNo(demand.getOrderNo());
            quotation.setState("否");
            quotation.setFile(demand.getFile());
            quotation.setAddTime(new Date());
            quotation.setCompany(demand.getReceiving());
            quotationService.insert(quotation);
        }catch (Exception e){
            e.printStackTrace();
            jsonUtil.setMsg("转换失败");
            return jsonUtil;
        }
        jsonUtil.setMsg("ok");
        return jsonUtil;
    }

    @PostMapping("/download")
    public void UserExcelDownloads(HttpServletResponse response, String id) throws IOException {
        TDemand quotation = demandService.selectByPrimaryKey(id);
        List<TProductDemand>  productDemands = productDemandService.selectListByOrderNo(quotation.getOrderNo());

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("需求单");
        sheet.setColumnWidth(0, 30 * 256);//设置列的宽度
        sheet.setColumnWidth(1, 30 * 256);//设置列的宽度
        sheet.setColumnWidth(2, 30 * 256);//设置列的宽度
        sheet.setColumnWidth(3, 30 * 256);//设置列的宽度
        sheet.setColumnWidth(4, 30 * 256);//设置列的宽度
        sheet.setColumnWidth(5, 30 * 256);//设置列的宽度
        String fileName = "体检信息" + ".xls";
        CellStyle style = workbook.createCellStyle();
        //水平垂直居中
        style.setAlignment(HorizontalAlignment.CENTER);//水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中

        CellStyle styleLeft = workbook.createCellStyle();
        //水平垂直居中
        styleLeft.setAlignment(HorizontalAlignment.LEFT);//水平居中
        styleLeft.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        styleLeft.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        styleLeft.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //第一行
        Row row0 = sheet.createRow(0);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
        row0.createCell(0).setCellValue("山东创联三维科技有限公司");
        row0.getCell(0).setCellStyle(style);
        sheet.getRow(0).setHeight((short) 1000);
        //第二行
        Row row1 = sheet.createRow(3);
        row1.createCell(0).setCellValue("序号");
        row1.createCell(1).setCellValue("样件名称");
        row1.createCell(2).setCellValue("设计类型");
        row1.createCell(3).setCellValue("材料类型");
        row1.createCell(4).setCellValue("工艺类型");
        row1.createCell(5).setCellValue("后处理要求");
        row1.createCell(6).setCellValue("数量");
        //第三行


        //第四行
        Row row3 = sheet.createRow(1);
        row3.createCell(0).setCellValue("重量");
        row3.createCell(1).setCellValue("工期");
        row3.createCell(2).setCellValue("外协打印（含税、含运费）");
        row3.createCell(3).setCellValue("外协后处理（含税、含运费）");
        row3.createCell(4).setCellValue("收货信息");

        //第五行
        Row row4 = sheet.createRow(2);
        row4.createCell(0).setCellValue(quotation.getWeight());
        row4.createCell(1).setCellValue(quotation.getPeriod());
        row4.createCell(2).setCellValue(quotation.getForeignPrient());
        row4.createCell(3).setCellValue(quotation.getForeignPrient());
        row4.createCell(4).setCellValue(quotation.getReceiving());

        for (int i = 0; i < productDemands.size(); i++) {
            Row rowi = sheet.createRow(i + 4);
            rowi.createCell(0).setCellValue(i + 1);
            TProductDemand productDemand = productDemands.get(i);
            rowi.createCell(1).setCellValue(productDemand.getSample());
            rowi.createCell(2).setCellValue(productDemand.getDesign());
            rowi.createCell(3).setCellValue(productDemand.getMaterial());
            rowi.createCell(4).setCellValue(productDemand.getTechnology());
            rowi.createCell(5).setCellValue(productDemand.getHandle());
            rowi.createCell(6).setCellValue(productDemand.getNumber());
        }

        //第六行
//        Row row5 = sheet.createRow(5);
//        sheet.addMergedRegion(new CellRangeAddress(5, 5, 0, 5));
//        row5.createCell(0).setCellValue("3D打印报价单");
//        row5.getCell(0).setCellStyle(style);
//        sheet.getRow(5).setHeight((short) 1000);
//        //第七行
//        Row row6 = sheet.createRow(6);
//        sheet.addMergedRegion(new CellRangeAddress(6, 6, 1, 5));
//        row6.createCell(0).setCellValue("公司名称：");
//        //第八行
//        Row row7 = sheet.createRow(7);
//        sheet.addMergedRegion(new CellRangeAddress(7, 7, 1, 5));
//        row7.createCell(0).setCellValue("收件地址：");
//        //第九行
//        Row row8 = sheet.createRow(8);
//        sheet.addMergedRegion(new CellRangeAddress(8, 8, 3, 5));
//        row8.createCell(0).setCellValue("联 系 人：");
//        row8.createCell(2).setCellValue("联系电话：");
//        //第十行
//        Row row9 = sheet.createRow(9);
//        sheet.addMergedRegion(new CellRangeAddress(9, 9, 1, 5));
//        row9.createCell(0).setCellValue("联系邮箱：");
//        row9.createCell(1).setCellValue("");
//        //第11行
//        Row row10 = sheet.createRow(10);
//        sheet.addMergedRegion(new CellRangeAddress(10, 10, 0, 5));
//        row10.createCell(0).setCellValue("设计");
//        row10.getCell(0).setCellStyle(styleLeft);
//        row10.setHeight((short) 1000);
//        //第12行
//        Row row11 = sheet.createRow(11);
//        row11.createCell(0).setCellValue("序号");
//        row11.createCell(1).setCellValue("样件名称");
//        row11.createCell(2).setCellValue("设计类型");
//        row11.createCell(3).setCellValue("数量/件");
//        row11.createCell(4).setCellValue("小计");
//        row11.createCell(5).setCellValue("合计/元");
//        //第13行到15行
//        for (int i = 0; i < productDemands.size(); i++) {
//            Row rowi = sheet.createRow(i + 12);
//            rowi.createCell(0).setCellValue(i + 1);
//            TProductDemand productDemand = productDemands.get(i);
//            rowi.createCell(1).setCellValue(productDemand.getSample());
//            rowi.createCell(2).setCellValue(productDemand.getDesign());
//            rowi.createCell(3).setCellValue(productDemand.getNumber());
//            rowi.createCell(4).setCellValue(productDemand.getSubtotal());
//        }
//        sheet.shiftRows(15, 15, -1);
//        //第17行
//        Row row16 = sheet.createRow(16);
//        sheet.addMergedRegion(new CellRangeAddress(16, 16, 0, 5));
//        row16.createCell(0).setCellValue("打印");
//        row16.getCell(0).setCellStyle(styleLeft);
//        sheet.getRow(16).setHeight((short) 1000);
//
//        //第18行
//        Row row17 = sheet.createRow(17);
//        row17.createCell(0).setCellValue("序号");
//        row17.createCell(1).setCellValue("样件名称");
//        row17.createCell(2).setCellValue("材料类型");
//        row17.createCell(3).setCellValue("数量/件");
//        row17.createCell(4).setCellValue("小计");
//        row17.createCell(5).setCellValue("合计/元");
//        //第19行到21行
//        for (int i = 0; i < productDemands.size(); i++) {
//
//            Row rowi = sheet.createRow(i + 18);
//            rowi.createCell(0).setCellValue(i + 1);
//            TProductDemand productDemand = productDemands.get(i);
//            rowi.createCell(1).setCellValue(productDemand.getSample());
//            rowi.createCell(2).setCellValue(productDemand.getMaterial());
//            rowi.createCell(3).setCellValue(productDemand.getNumber());
//            rowi.createCell(4).setCellValue(productDemand.getSubtotal());
//        }
//        //第22行
//        Row row21 = sheet.createRow(21);
//        sheet.addMergedRegion(new CellRangeAddress(21, 21, 0, 5));
//        row21.createCell(0).setCellValue("后处理");
//        row21.getCell(0).setCellStyle(styleLeft);
//        sheet.getRow(21).setHeight((short) 1000);
//        //第23行
//        Row row22 = sheet.createRow(22);
//        row22.createCell(0).setCellValue("序号");
//        row22.createCell(1).setCellValue("样件名称");
//        row22.createCell(2).setCellValue("工艺类型");
//        row22.createCell(3).setCellValue("数量/件");
//        row22.createCell(4).setCellValue("小计");
//        row22.createCell(5).setCellValue("合计/元");
//        //第24行到26行
//        for (int i = 0; i < productDemands.size(); i++) {
//            Row rowi = sheet.createRow(i + 23);
//            rowi.createCell(0).setCellValue(i + 1);
//            TProductDemand productDemand = productDemands.get(i);
//            rowi.createCell(1).setCellValue(productDemand.getSample());
//            rowi.createCell(2).setCellValue(productDemand.getTechnology());
//            rowi.createCell(3).setCellValue(productDemand.getNumber());
//            rowi.createCell(4).setCellValue(productDemand.getSubtotal());
//
//        }
//        //第27行
//        Row row26 = sheet.createRow(26);
//        sheet.addMergedRegion(new CellRangeAddress(26, 26, 0, 5));
//        //第28行
//        Row row27 = sheet.createRow(27);
//        sheet.addMergedRegion(new CellRangeAddress(27, 27, 0, 1));
//        sheet.addMergedRegion(new CellRangeAddress(27, 27, 2, 5));
//        row27.createCell(0).setCellValue("合计/元：");
//        //第29行
//        Row row28 = sheet.createRow(28);
//        sheet.addMergedRegion(new CellRangeAddress(28, 28, 0, 1));
//        sheet.addMergedRegion(new CellRangeAddress(28, 28, 2, 5));
//        row28.createCell(0).setCellValue("税点：");
//        //第30行
//        Row row29 = sheet.createRow(29);
//        sheet.addMergedRegion(new CellRangeAddress(29, 29, 0, 1));
//        sheet.addMergedRegion(new CellRangeAddress(29, 29, 2, 5));
//        row29.createCell(0).setCellValue("运费：");
//        //第31行
//        Row row30 = sheet.createRow(30);
//        sheet.addMergedRegion(new CellRangeAddress(30, 30, 0, 1));
//        sheet.addMergedRegion(new CellRangeAddress(30, 30, 2, 5));
//        row30.createCell(0).setCellValue("总合计/元（大写人民币）：");
//        //第32行
//        Row row31 = sheet.createRow(31);
//        //第33行
//        Row row32 = sheet.createRow(32);
//        sheet.addMergedRegion(new CellRangeAddress(32, 32, 0, 5));
//        row32.createCell(0).setCellValue("付款信息");
//
//        //第34行
//        Row row33 = sheet.createRow(33);
//        sheet.addMergedRegion(new CellRangeAddress(33, 33, 0, 5));
//        row33.createCell(0).setCellValue("名    称：山东创联三维科技有限公司");
//
//        //第35行
//        Row row34 = sheet.createRow(34);
//        sheet.addMergedRegion(new CellRangeAddress(34, 34, 0, 5));
//        row34.createCell(0).setCellValue("开户银行：中信银行股份有限公司济宁分行");
//
//        //第36行
//        Row row35 = sheet.createRow(35);
//        sheet.addMergedRegion(new CellRangeAddress(35, 35, 0, 5));
//        row35.createCell(0).setCellValue("  银行账户：8112501011900778195");
//
//        //第37行
//        Row row36 = sheet.createRow(36);
//        sheet.addMergedRegion(new CellRangeAddress(36, 41, 0, 5));
//        row36.createCell(0).setCellValue("    备注：\n" +
//                "1、此金额含：增值税发票。\n" +
//                "2、运费说明：以上价格含运费，超出最低起运标准，按快递公司收费标准另行收取。\n" +
//                "3、付款说明：（1）单结，方式按照合同规定执行； \n" +
//                "            （2）只接受支票、电汇、转账、微信、支付宝，不收期票和银行承兑汇票。          \n" +
//                "4、报价有效期限：此报价单有效期为报价日期起15天内。");
//
//        //第43行
//        Row row42 = sheet.createRow(42);
//        //第44行
//        Row row43 = sheet.createRow(43);
//        sheet.addMergedRegion(new CellRangeAddress(43, 43, 2, 5));
//        row43.createCell(0).setCellValue("公司名称：");
//        row43.createCell(1).setCellValue("（公章）");
//        row43.createCell(2).setCellValue("山东创联三维科技有限公司");
//        //第45行
//        Row row44 = sheet.createRow(44);
//        //第46行
//        Row row45 = sheet.createRow(45);
//        row43.createCell(0).setCellValue("审核：");
//        //第47行
//        Row row46 = sheet.createRow(46);
//        //第48行
//        Row row47 = sheet.createRow(47);
//        sheet.addMergedRegion(new CellRangeAddress(47, 47, 3, 5));
//        row47.createCell(3).setCellValue("本报价单盖章后有效");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");

        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
}
